package com.specialized.common.core.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;



public class DesUtils {
    //秘钥
    private static final String KEY = "~@#$y1a2n.&@+n@$%*(1)";
    //加密算法
    private static final String  ALGORITHM = "DES";
    //编码
    private static final String CHARSET = "UTF-8";

    /**
     * byte数组转换成十六进制字符串
     * @param bytes byte数组
     * @return
     */
    private static String bytesToHexStr(byte[] bytes) {
        String tmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < bytes.length; i++) {
            tmp = Integer.toHexString(bytes[i] & 0xFF);
            sb.append((tmp.length() == 1) ? "0" + tmp : tmp);
        }
        return sb.toString().toUpperCase().trim();
    }
    /**
     * 十六进制字符串转成byte数组
     * @param hexStr   十六进制字符串
     * @return
     * */
    private static byte[] hexStrToBytes(String hexStr) {
        byte[] bytes = new byte[hexStr.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hexStr.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }
    /**
     * @param key   秘钥
     * @param encodeStr  需要加密的字符串
     * @return
     */
    public static String encodeDES(String key, String encodeStr) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKey secretKey = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(new DESKeySpec(key.getBytes()));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encrypted = cipher.doFinal(encodeStr.getBytes(CHARSET));
        return bytesToHexStr(encrypted);
    }

    /**
     * @param key          秘钥
     * @param decodeStr   需要解密的字符串
     * @return
     */
    public static String decodeDES(String key, String decodeStr) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKey secretKey = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(new DESKeySpec(key.getBytes()));
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedString = cipher.doFinal(hexStrToBytes(decodeStr));
        return new String(decodedString, CHARSET);
    }
}
